package guiPackage;
import businessLogic.*;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
//import java.sql.Date;
//import java.awt.image.BufferedImage;
//import java.io.File;
//import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Map;

import javax.swing.JScrollPane;

import businessLogic.*;

//import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.JXDatePicker;

//import java.util.Date;






//import javax.imageio.ImageIO;
import javax.swing.*;

//import mainScreen.AdminFunctions.AdminButtonHandler1;
//import mainScreen.AdminFunctions.AdminButtonHandler2;
//import mainScreen.AdminFunctions.AdminButtonHandler3;
//import mainScreen.AdminFunctions.AdminFunctionsMainPanel;
//import businessLogic.*;

//import basicComponents.ButtonDemo2.ButtonHandler;

public class MainPage extends JFrame
{
	JFrame mainFrame; 
	MainPanel titlePanel, buttonsPanel, searchPanel , adminPanel, displayPanel;
	AdminFunctionsMainPanel adminTitlePanel, adminFunctionPanel, leftPanel, adminDisplayPanel, bottomPanel;
	
	JTextArea display = new JTextArea(16,111);
	JTextArea adminDisplay = new JTextArea(29,39);
	
	JScrollPane scrollBar, adminScrollBar; 
	
	//ImageIcon image = new ImageIcon("books.jpg");
	
	//JLabel imageLabel = new JLabel("", image, JLabel.CENTER);
	
	//MainPanel groupBoxEncryption = new MainPanel(); 
	
		
	JButton clear = new JButton("Clear");
	JButton adminClear = new JButton("Clear Display Area");
	
	AutomatedAssistant autoAssistant;
	
	//Container contentPane = mainFrame.getContentPane();
	
		
	public MainPage(String membersFilename, String catalogFilename, String transactionsFilename)throws NumberFormatException, ParseException
	{
		display.setEditable(false);
		scrollBar = new JScrollPane(display);
		scrollBar.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		
		transactionHistoryStartPicker.setDate(Calendar.getInstance().getTime());
		transactionHistoryStartPicker.setFormats(new SimpleDateFormat("MM/dd/yyyy"));
		
		transactionHistoryEndPicker.setDate(Calendar.getInstance().getTime());
		transactionHistoryEndPicker.setFormats(new SimpleDateFormat("MM/dd/yyyy"));
				
    	autoAssistant = new AutomatedAssistant(membersFilename, catalogFilename, transactionsFilename);

    	mainFrame = new JFrame("Home Page");
		mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		mainFrame.addWindowListener( new WindowAdapter()
		{
		    public void windowClosing(WindowEvent e)
		    {
		        JFrame frame = (JFrame)e.getSource();

		        int result = JOptionPane.showConfirmDialog(
		            frame,
		            "Are you sure you want to exit the application?",
		            "Exit Application",
		            JOptionPane.YES_NO_OPTION);

		        if (result == JOptionPane.YES_OPTION)
		        {
					try {
						autoAssistant.persistLibrary();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		        }
		    }
		});
		
			
	
		
        mainFrame.setPreferredSize(new Dimension(1000,1000));
        
        setLayout(new BorderLayout());
        
        titlePanel = new MainPanel(Color.RED);
        titlePanel.setPreferredSize(new Dimension(150,100));
        titlePanel.setBorder(BorderFactory.createMatteBorder(9, 9, 9, 9, Color.black));
        titlePanel.setTitlePanel();
        
        adminTitlePanel = new AdminFunctionsMainPanel(Color.RED);
		adminTitlePanel.setPreferredSize(new Dimension(50,75));
		adminTitlePanel.setBorder(BorderFactory.createMatteBorder(9, 9, 9, 9, Color.black));
		adminTitlePanel.setAdminTitlePanel();
        
        buttonsPanel = new MainPanel(Color.orange);
        buttonsPanel.setBorder(BorderFactory.createMatteBorder(0, 8, 8, 8, Color.black));
        buttonsPanel.setButtonsPanel();
        
        leftPanel = new AdminFunctionsMainPanel(Color.red);
		leftPanel.setBorder(BorderFactory.createMatteBorder(0, 8, 0, 8, Color.black));
        
        searchPanel = new MainPanel(Color.cyan);
        searchPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 8, 8, Color.black));
        searchPanel.setSearchPanel();
        
        adminFunctionPanel = new AdminFunctionsMainPanel(Color.pink);
		adminFunctionPanel.setFunctionPanel();
        
        adminPanel = new MainPanel(Color.yellow);
        adminPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 8, 8, Color.black));
        adminPanel.setPreferredSize(new Dimension(400,300));
        adminPanel.setAdminPanel();
        
        bottomPanel = new AdminFunctionsMainPanel(Color.red);
		bottomPanel.setBorder(BorderFactory.createMatteBorder(8, 0, 8, 0, Color.black));
        
        displayPanel = new MainPanel(Color.pink);
        displayPanel.setBorder(BorderFactory.createMatteBorder(0, 8, 8, 8, Color.black));
        displayPanel.setPreferredSize(new Dimension(300,300));
        //displayPanel.add(display);
        displayPanel.add(scrollBar);
        displayPanel.setDisplayPanel();
        
        adminDisplayPanel = new AdminFunctionsMainPanel(Color.lightGray);
		adminDisplayPanel.setPreferredSize(new Dimension(600,600));
		adminDisplayPanel.setBorder(BorderFactory.createMatteBorder(0, 8, 0, 0, Color.black));
		adminDisplayPanel.add(adminScrollBar);
		adminDisplayPanel.setAdminDisplayPanel();
        
                
		Container contentPane = mainFrame.getContentPane();
        
        contentPane.add(titlePanel, BorderLayout.NORTH);
       	contentPane.add(displayPanel, BorderLayout.SOUTH);
       	contentPane.add(adminPanel, BorderLayout.EAST);
       	contentPane.add(buttonsPanel, BorderLayout.WEST);
       	contentPane.add(searchPanel, BorderLayout.CENTER);
       	
       	mainFrame.pack();
        mainFrame.setVisible(true);
	}
	public void dispose()
	{
		try {
			autoAssistant.persistLibrary();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		super.dispose();
	}
	
	public static void main(String[] args) throws NumberFormatException, ParseException 
    {
    	new MainPage(args[0], args[1], args[2]);
 	}
    
    JTextField cardnum = new JTextField(10);
    JTextField itemno = new JTextField(10);
    JTextField fname = new JTextField(20);
    JTextField lname = new JTextField(20);
    JTextField county = new JTextField(20);
    JTextField email = new JTextField(30);
    JTextField fineAmt = new JTextField(20);

    private class CheckOutButtonHandler implements ActionListener 
    {
    	// handle button event
    	public void actionPerformed( ActionEvent event )
    	{
    		Object[] message = 
    			{
    				"Enter Your Card Number and Item Number\n",
    				"Card Num:", cardnum,
    				"Item Num:", itemno
    			};

    		int option = JOptionPane.showConfirmDialog(null, message, "Member Authentication", JOptionPane.OK_CANCEL_OPTION);
    		if (option == JOptionPane.OK_OPTION) 
    		{
    			String cardNo, itemNo;
    			cardNo = cardnum.getText();
    			itemNo = itemno.getText();

    			if(autoAssistant.validateMember(cardNo) && autoAssistant.validateItem(itemNo))
    			{
    				Collection<Item> checkedOutItems = autoAssistant.itemCheckout(cardNo,itemNo);
    				int count = checkedOutItems.size();
    				if (count > 0)
    				{
    					display.setText("");
    					display.append("The requested Item has been successfully checked out\n");
    					display.append("Member ID:"+cardNo + "\n");
    					display.append("Number of Checked Out Items:" +count + "\n");
    					display.append("List of checked out Items:"+"\n\n");
    					display.append("\tItem\tDue Date\t\tBorrowed Date\n");

    					for(Item itemsCheckedOut: checkedOutItems)
    					{
    						display.append(itemsCheckedOut.toString()+ "\n");    	    		
    					}
    				}
    			}
    		} 
    		else 
    		{
    			display.append("Action cancelled\n");
    		}
    	}
    }
    
    private class ReturnButtonHandler implements ActionListener 
    {
    	// handle button event
    	public void actionPerformed( ActionEvent event )
    	{
    		//StringBuilder displayMessage = new StringBuilder();
    		Object[] message = 
    			{
    				"Enter Your Card Number and Item Number\n",
    				"Card Num:", cardnum,
    				"Item Num:", itemno
    			};

    		int option = JOptionPane.showConfirmDialog(null, message, "Member Authentication", JOptionPane.OK_CANCEL_OPTION);
    		if (option == JOptionPane.OK_OPTION) 
    		{
    			String cardNo, itemNo;
    			//boolean validCard, validItem, 
       			cardNo = cardnum.getText();
    			itemNo = itemno.getText();

    			if(autoAssistant.validateMember(cardNo) && autoAssistant.validateItem(itemNo))
    			{
    				double itemReturned = autoAssistant.itemReturn(cardNo,itemNo);
    			}
    		} 
    		else 
    		{
    			//System.out.println("Login canceled");
    			display.append("Action cancelled\n");
    		}
    	}
    }
    
    private class ReserveButtonHandler implements ActionListener 
    {
        // handle button event
        public void actionPerformed( ActionEvent event )
        {
        	//StringBuilder displayMessage = new StringBuilder();
        	Object[] message = 
    	    {
        			"Enter Your Card Number and Item Number\n",
    	        	"Card Num:", cardnum,
    	        	"Item Num:", itemno
    	    };
    	        
    	    int option = JOptionPane.showConfirmDialog(null, message, "Member Authentication", JOptionPane.OK_CANCEL_OPTION);
    	    if (option == JOptionPane.OK_OPTION) 
    	    {
    	    	String cardNo, itemNo;
    	    	cardNo = cardnum.getText();
    	    	itemNo = itemno.getText();

    	    	if(autoAssistant.validateMember(cardNo) && autoAssistant.validateItem(itemNo))
    	    	{
    	    		Collection<Item> reservedItems = autoAssistant.itemReserve(cardNo, itemNo);


    	    		if(reservedItems.isEmpty())
    	    		{
    	    			display.setText("");
    	    			display.append("There are no previous reservations in your name");
    	    		}
    	    		else
    	    		{

    	    			display.setText("");
    	    			display.append("Member ID:"+cardNo + "\n");
    	    			//display.append("Number of Checked Out Items:" +count + "\n");
    	    			display.append("List of Reserved Items:"+"\n\n");
    	    			//display.append("\tItem\tBorrowed Date\tDue Date\n");

    	    			for(Item itemsReserved: reservedItems)
    	    			{
    	    				display.append(itemsReserved.getTitle());    	    		
    	    			}
    	    		}
    	    	}

    	    } 
        	else 
        	{
        		//System.out.println("Login canceled");
        	    display.append("Action cancelled\n");
        	}
        }
     }
    
    private class FineHandler implements ActionListener 
    {
    	// handle button event
    	public void actionPerformed( ActionEvent event )
    	{
    		//StringBuilder displayMessage = new StringBuilder();
    		Object[] message = 
    			{
    				"Enter Your Card Number and Item Number\n",
    				"Card Num:", cardnum,
    				"Fine Amount:", fineAmt
    			};

    		int option = JOptionPane.showConfirmDialog(null, message, "Member Authentication", JOptionPane.OK_CANCEL_OPTION);
    		if (option == JOptionPane.OK_OPTION) 
    		{
    			String cardNo,fineAmount; 
    			double fine;
    			cardNo = cardnum.getText();
    			fineAmount = fineAmt.getText();
    			fine = Integer.parseInt(fineAmount);


    			if(autoAssistant.validateMember(cardNo))
    			{
    			//autoAssistant.validateItem(itemNo);

    			double remainingFine = autoAssistant.payFine(cardNo,fine);
    			
    			display.append("Your outstanding fine balance is: $" +remainingFine );
    			}
    		} 
    		else 
    		{
    			//System.out.println("Login canceled");
    			display.append("Action cancelled\n");
    		}
    	}
     }
    
    
    JXDatePicker transactionHistoryStartPicker = new JXDatePicker();
	JXDatePicker transactionHistoryEndPicker = new JXDatePicker();
	
		
     private class TransactionHistoryHandler implements ActionListener
     {
    	 public void actionPerformed( ActionEvent event )
    	 {
    		 Object[] message = 
    		 {
         		"Enter Your Card Number to view Your transaction History\n",
     	        "Card Num: ", cardnum ,
     	        "Start Date: ", transactionHistoryStartPicker,
     	        "End Date: ", transactionHistoryEndPicker 
     	     };
     	       
     	     int option = JOptionPane.showConfirmDialog(null, message, "Member Authentication", JOptionPane.OK_CANCEL_OPTION);
     	     
     	     if (option == JOptionPane.OK_OPTION) 
     	     {
     	    	 String cardNo;
     	    	 java.util.Date transactionStartDate, transactionEndDate;
     	    	 cardNo = cardnum.getText();
     	    	 transactionStartDate = transactionHistoryStartPicker.getDate();
     	    	 transactionEndDate = transactionHistoryEndPicker.getDate();


     	    	 if(autoAssistant.validateMember(cardNo))
     	    	 {

     	    		 ArrayList<Transaction> transactionHistory = autoAssistant.showTransactionHistory(cardNo, transactionStartDate, transactionEndDate);
     	    		 display.setText("");
     	    		 if(transactionHistory.isEmpty())
     	    		 {
     	    			 display.append("There are no transactions over the selected period ");
     	    		 }
     	    		 else
     	    		 {
     	    			 display.append("\tTran-Id\tTran-Date\t\tTran-type\t\tMemberId\tItemId\tFineAmount\n");
     	    			 for(Transaction transHistory: transactionHistory)
     	    				 display.append(transHistory.toString() + "\n");
     	    		 }
     	    	 }

     	     } 
    		else 
    		{
    			//System.out.println("Login canceled");
    			display.append("Action cancelled\n");
    		}
     	     
    	 }
    	 
     }
     
     private class RegisterHandler implements ActionListener
     {
    	 public void actionPerformed( ActionEvent event )
    	 {
    		 Object[] message = 
    			 {
         				"Please fill in the following Details.\n",
     	        	    "First Name:", fname,
     	        	    "Last Name:", lname,
     	        	    "City:", county,
     	        	    "E-Mail ID:", email
    			 };
     	        
    		 int option = JOptionPane.showConfirmDialog(null, message, "Member Authentication", JOptionPane.OK_CANCEL_OPTION);
     	          	       
     	        
    		 if (option == JOptionPane.OK_OPTION) 
    		 {
    			 String firstName,lastName,countyName,emailAddress, newMemberId;
    			 //s5 = null;
    			 firstName = fname.getText();
    			 lastName = lname.getText();
    			 countyName = county.getText();
    			 countyName = countyName.toLowerCase();
    			 emailAddress = email.getText();
    			 if ("".equals(firstName) || "".equals(lastName) || "".equals(countyName) || "".equals(emailAddress)) 
    			 {
    				 JOptionPane.showMessageDialog(null, "Please fill in completely. All the fields are mandatory");
    			 }
    			 else if(!(countyName.equals("springfield")) && !("".equals(countyName)))
         	     {
    
         	    	 //JOptionPane.showMessageDialog(null, "Please pay an amount of $10 to complete your registration");
    				 int newoption = JOptionPane.showConfirmDialog(null, "Please pay a fee of $10.0 to complete your registration", "Out of county fee", JOptionPane.OK_CANCEL_OPTION);
    				 if(newoption == JOptionPane.OK_OPTION)
    				 {
    					 JOptionPane.showMessageDialog(null, "Thank you for your payment", "PAYMENT RECEIVED", JOptionPane.PLAIN_MESSAGE);
    					 newMemberId = autoAssistant.registerNewMember(firstName, lastName, emailAddress);
    					 display.append("");
    					 display.append("Congratulations!! You are now a member\n" );
    					 display.append("Your new memberId is: " +newMemberId);
    				 }
    				 else
    				 {
    					 display.append("");
    					 display.append("Registration Cancelled");
    				 }
         	     }
    			 else 
    			 {
    				 newMemberId = autoAssistant.registerNewMember(firstName, lastName, emailAddress);
    				 //System.out.println("login failed");
    				 //JOptionPane.showMessageDialog(null, "Congratulations!! You are now a member of the library");
    				 display.append("");
    				 display.append("Congratulations!! You are now a member\n" );
    				 display.append("Your new memberId is: " +newMemberId);
    			 }

    		 } 
    		 else 
    		 {
    			 //System.out.println("Login canceled");
    			 JOptionPane.showMessageDialog(null,"Action Cancelled\n");
    		 }
    	 }
     }
     
     private class LoginHandler implements ActionListener
     {
    	 public void actionPerformed( ActionEvent event )
    	 {
    		 String uname,pwd;
    		 uname = userName.getText();
    		 pwd = password.getText();

    		 boolean logInSuccess = autoAssistant.validateAdminCredentials(uname, pwd);
    		 //String message = "Login Successful";
    		 //String title = "Login Successful";

    		 if(logInSuccess == true)
    		 {
    			 userName.setText("");
    			 password.setText("");
    			 JOptionPane.showMessageDialog(null, "Login Successful");
    			 titlePanel.setVisible(false);
    			 buttonsPanel.setVisible(false);
    			 searchPanel.setVisible(false);
    			 displayPanel.setVisible(false);
    			 adminPanel.setVisible(false);

    			 Container contentPane = mainFrame.getContentPane();
    			 contentPane.add(adminTitlePanel, BorderLayout.NORTH);
    			 contentPane.add(leftPanel, BorderLayout.WEST);
    			 contentPane.add(adminDisplayPanel, BorderLayout.EAST);
    			 contentPane.add(bottomPanel, BorderLayout.SOUTH);
    			 contentPane.add(adminFunctionPanel, BorderLayout.CENTER);

    			 mainFrame.setVisible(true);

    		 }
    		 else
    		 {
    			 userName.setText("");
    			 password.setText("");
    		 }


    	 }

     }
     
     private class SearchHandler implements ActionListener
     {
    	 public void actionPerformed( ActionEvent e )
    	 {
    		 String searchItem;
    		 searchItem = search.getText();

    		 ArrayList<Item> searchResult = autoAssistant.searchItems(searchItem);
    		 //Item book = new Book();
    		 //Item video = new Video();
    		 


    		 if(searchResult.isEmpty())
    		 {
    			 display.setText("");
    			 display.append("\tNo matches found\n");
    		 }
    		 else
    		 {
    			 display.setText("");
    			 display.append("\tSearch Results:\n");
    			 display.append("\tTitle \t Category \t\t Type \t Location \t Author/Director\n");
    			 for(Item searchResults : searchResult )
    			 {
    				 display.append("\t" + searchResults.getItemDetails() + "\n");
    			 }

    				   
    		 }

    	 }

     }
     
     JTextField search = new JTextField(20);
         
     private class ClearHandler implements ActionListener
     {
    	 public void actionPerformed( ActionEvent e )
    	 {
    		 String s = "";
        	 display.setText(s);
        	 search.setText(s);
    		     		 
    	 }
    	 
     }
     
     //JTextField userName, password;
     JTextField userName = new JTextField(15);
     JTextField password = new JPasswordField(15);
     
    //Inner class for panels
    class MainPanel extends JPanel 
    {
    			
		JButton register, checkOutItem, returnItem, reserveItem, payFine, transactionHistory, submit, login, memberLogin;
		JTextField cardnum, itemno;
		JLabel searchItem, username,passwd, adminLogin, mainLbl, cardNum, itemNum, fname, lname, county, email;
		
		//JScrollPane scrollBar = new JScrollPane(display);
		//JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL);
		
				
				
		public MainPanel(Color color)
		{
			//vbar.setLocation(1500,1500);
			//vbar.setBounds(3, 3, 300, 200);
			//vbar.
			setBackground(color);
			
			//create instances for buttons
			register = new JButton("Register");
			checkOutItem = new JButton("Check Out an Item");
			returnItem = new JButton("Return an Item");
			reserveItem = new JButton("Reserve an Item");
			payFine = new JButton("Pay Fine");
			transactionHistory = new JButton("View Transaction History");
			submit = new JButton("Search");
			login = new JButton("Log In");
			memberLogin = new JButton("Submit");
			//clear = new JButton("Clear");
			
			//create instances for text Fields
			//search = new JTextField(20);
			//userName = new JTextField(20);
			//password = new JPasswordField(20);
			cardnum = new JTextField(7);
			itemno = new JTextField(7);
			
					
						
			//create labels
			searchItem = new JLabel("Search for an Item", SwingConstants.CENTER);
			username = new JLabel("Admin UserID");
			passwd = new JLabel("Password");
			adminLogin = new JLabel("Admin Login");
			cardNum = new JLabel("Card Number");
			itemNum = new JLabel("Item Number");
			fname = new JLabel("First Name");
			lname = new JLabel("Last Name");
			county = new JLabel("County");
			email = new JLabel("Email-ID");
			
			   	
	    	checkOutItem.addActionListener(new CheckOutButtonHandler());
	    	returnItem.addActionListener(new ReturnButtonHandler());
	    	reserveItem.addActionListener(new ReserveButtonHandler());
	    	payFine.addActionListener(new FineHandler());
	    	transactionHistory.addActionListener(new TransactionHistoryHandler());
	    	register.addActionListener(new RegisterHandler());
	    	login.addActionListener(new LoginHandler());
	    	clear.addActionListener(new ClearHandler());
	    	submit.addActionListener(new SearchHandler());
	    	setSize(600,300);
	        setVisible( true );
		
		}
		
		public void setTitlePanel()
		{
			mainLbl = new JLabel("SPRINGFIELD COUNTY LIBRARY");
			mainLbl.setFont(new Font("Times New Roman", Font.BOLD, 50));
			mainLbl.setForeground(Color.BLACK);
			titlePanel.add (mainLbl);
		}
		
		public void setButtonsPanel()
		{
			buttonsPanel.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
			add(Box.createRigidArea(new Dimension(0, 15)));
			buttonsPanel.add(register);
			add(Box.createRigidArea(new Dimension(0, 15)));
			buttonsPanel.add(checkOutItem);
			add(Box.createRigidArea(new Dimension(0, 15)));
			buttonsPanel.add(returnItem);
			add(Box.createRigidArea(new Dimension(0, 15)));
			buttonsPanel.add(reserveItem);
			add(Box.createRigidArea(new Dimension(0, 15)));
			buttonsPanel.add(payFine);
			add(Box.createRigidArea(new Dimension(0, 15)));
			buttonsPanel.add(transactionHistory);
				
		}
		
		public void setSearchPanel()
		{
			searchPanel.setLayout(new FlowLayout());
			searchItem.setFont(new Font("Times New Roman", Font.BOLD, 20));
			searchItem.setForeground(Color.BLACK);
			searchPanel.add(searchItem);
			add(Box.createRigidArea(new Dimension(10, 0)));
			searchPanel.add(search);
			add(Box.createRigidArea(new Dimension(10, 0)));
			searchPanel.add(submit);
			searchPanel.add(clear);
			
		}
		
		public void setAdminPanel()
		{
			adminPanel.setLayout(new GridBagLayout());
			GridBagConstraints c = new GridBagConstraints();
			username.setFont(new Font("Times New Roman", Font.BOLD, 15));
			passwd.setFont(new Font("Times New Roman", Font.BOLD, 15));
			c.gridx = 0;
			c.gridy = 0;
			adminPanel.add(username,c);
			//add(Box.createRigidArea(new Dimension(10, 10)));
			c.gridx = 1;
			c.gridy = 0;
			adminPanel.add(userName,c);
			c.gridx = 0;
			c.gridy = 1;
			adminPanel.add(passwd,c);
			c.gridx = 1;
			c.gridy = 1;
			adminPanel.add(password,c);
			//adminPanel.setLayout(new BoxLayout(adminPanel, BoxLayout.Y_AXIS));
			add(Box.createRigidArea(new Dimension(10, 0)));
			adminPanel.add(login);
			
		}
		public void setDisplayPanel()
		{
			displayPanel.setLayout(new FlowLayout());
			display.setFont(new Font("Times New Roman", Font.BOLD, 15));
			display.setBackground(Color.pink);
			display.setForeground(Color.black);
			add(Box.createRigidArea(new Dimension(0,0)));
			//displayPanel.add(scrollBar);
			//displayPanel.add(display);
			display.setEditable(false);
			//scrollBar.setBounds(3, 3, 300, 200);
			//scrollBar.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
			scrollBar.setVisible(true);
			
			//displayPanel.add(vbar);
			
		}
	
	}
    
    class AdminFunctionsMainPanel extends JPanel
	{
    	JXDatePicker picker1 = new JXDatePicker();
    	JXDatePicker picker2 = new JXDatePicker();
    	    	    	
    	private class AdminMemberCountHandler implements ActionListener
        {
    		public void actionPerformed( ActionEvent event )
       	 	{
    			adminDisplay.setText("");
    			int memberCount;
    			memberCount = autoAssistant.totalNoOfMembers();
    			adminDisplay.append("The Member Count for the library is: " + memberCount + "\n");
    			/*JOptionPane.showMessageDialog( null,
    		            "You pressed:" + event.getActionCommand() );*/
        
       	 	}
       	 
        }
    	
    	private class AdminItemsCheckedOutHandler implements ActionListener
        {
    		public void actionPerformed( ActionEvent event )
       	 	{
    			adminDisplay.setText("");
    			int numOfItemsBorrowed;
    			numOfItemsBorrowed = autoAssistant.noOfItemsBorrowed();
    			adminDisplay.append("The total number of items borrowed are :" + numOfItemsBorrowed + "\n");
    			/*JOptionPane.showMessageDialog( null,
    		            "You pressed:" + event.getActionCommand() );*/
        
       	 	}
       	 
        }
    	
    	private class TotalNumberOfItemsInEveryCategoryHandler implements ActionListener
        {
    		public void actionPerformed( ActionEvent event )
       	 	{
    			adminDisplay.setText("");
    			Map<String, Integer> totalItemsInEachCategory = autoAssistant.totalNoOfBooksAndVideosinLibrary();
    			adminDisplay.append("The total Number of Items in each category are as follows: \n");
    			for(Map.Entry<String, Integer> entry : totalItemsInEachCategory.entrySet())
    			{
    			adminDisplay.append(entry + "\n" );
    			}
    			
       	 	}
       	 
        }
    	
    	private class LogOutHandler implements ActionListener
    	{
    		public void actionPerformed( ActionEvent event )
       	 	{
    			String logout = "LogOut";
    			/*JOptionPane.showMessageDialog( null,
    		            "You have been successfully logged Out" );*/
    			String cmd = event.getActionCommand();
    			if (cmd.equals(logout))
    			{
    				JOptionPane.showMessageDialog( null, "You have been successfully logged Out" );
    				adminTitlePanel.setVisible(false);
    				adminFunctionPanel.setVisible(false);
    				leftPanel.setVisible(false);
    				adminDisplayPanel.setVisible(false);
    				bottomPanel.setVisible(false);
    				
    				
    				titlePanel.setVisible(true);
    	    		buttonsPanel.setVisible(true);
    	    		searchPanel.setVisible(true);
    	    		displayPanel.setVisible(true);
    	    		adminPanel.setVisible(true);
    				
    			}
    				  				
        
       	 	}
    		
    	}
    	
    	private class AdminClearHandler implements ActionListener
    	{
    		public void actionPerformed( ActionEvent event )
    		{
    			String s = "";
    			adminDisplay.setText(s);
           	}
    	}
    	
    	//JTextField startDate = new JTextField(20);
    	//JTextField endDate = new JTextField(20);
    	
    	//JXDatePicker picker = new JXDatePicker();
    	
    	private class AdminBooksCheckedOutHandler implements ActionListener
    	{
    		public void actionPerformed( ActionEvent event )
    		{
    			Object[] message = 
    				{
    					"Please fill in the following Details.\n",
    					"Start Date (Format: mm/dd/yyyy) :", picker1,
    					"End Date (Format: mm/dd/yyyy) :", picker2,

    				};

    			int option = JOptionPane.showConfirmDialog(null, message, "Admin Privilage", JOptionPane.OK_CANCEL_OPTION);
    			if (option == JOptionPane.OK_OPTION) 
    			{
    				java.util.Date startDate,endDate;
    				//String endDate;
    				startDate = picker1.getDate();
    				//adminDisplay.append(startDate + "\n");
    				endDate = picker2.getDate();
    				//adminDisplay.append(endDate + "\n");

    				adminDisplay.setText("");

    				Map<String, Integer> booksThatAreCheckedOutMost = autoAssistant.bookCheckedOutTheMost(startDate, endDate);

    				if(booksThatAreCheckedOutMost.isEmpty())
    				{
    					adminDisplay.append("There is no item that was most frequently checked out over the specified period\n");
    				}
    				else
    				{
    					adminDisplay.append("The books checked out the most are as follows: \n");
    	    			for(Map.Entry<String, Integer> entry : booksThatAreCheckedOutMost.entrySet())
    	    			{
    	    			adminDisplay.append(entry + "\n" );
    	    			}
    				}
    	    			
    			} 
    			else 
    			{
    				display.append("Request cancelled\n");
    			}

    		}
    	}

    	
    	
    	private class FineCollectedHandler implements ActionListener
    	{
    		public void actionPerformed( ActionEvent event )
    		{
    			Object[] message = 
          			 {
               				"Please fill in the following Details.\n",
           	        	    "Start Date (Format: mm/dd/yyyy) :", picker1,
           	        	    "End Date (Format: mm/dd/yyyy) :", picker2,
           	        	        	    
          			 };
           	        
          		 int option = JOptionPane.showConfirmDialog(null, message, "Admin Privilage", JOptionPane.OK_CANCEL_OPTION);
          		if (option == JOptionPane.OK_OPTION) 
            	{
          			adminDisplay.setText("");
        	    	java.util.Date startDate,endDate;
					startDate = picker1.getDate();
        	    	endDate = picker2.getDate();
        	    	      	    	
        	    	double totalFineAmount = autoAssistant.getTotalFineAmount(startDate, endDate);
        	    	
        	    	adminDisplay.append("The total fine amount collected over the period selected is: " + totalFineAmount + "\n");
        	   
        	    	
        	    } 
            	else 
            	{
            		//System.out.println("Login canceled");
            	    display.append("Request cancelled\n");
            	}
    		}
    	}
    	
    	JLabel mainLbl;
		JButton membercnt, itemschkdout, finesCollected, itemsByCategory, bookCheckedOutMost, logout;
		//AdminButtonHandler1 handler1, handler2, handler3, handler4, handler5;
		//AdminButtonHandler2 handler6;
		//AdminButtonHandler3 handler7;
	
		
		public AdminFunctionsMainPanel(Color color)
		{
			adminDisplay.setEditable(false);
			adminScrollBar = new JScrollPane(adminDisplay);
			adminScrollBar.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
			
			picker1.setDate(Calendar.getInstance().getTime());
	        picker1.setFormats(new SimpleDateFormat("MM/dd/yyyy"));
	        
	        picker2.setDate(Calendar.getInstance().getTime());
	        picker2.setFormats(new SimpleDateFormat("MM/dd/yyyy"));
	        
			//mainFrame.pack();
    		mainFrame.setVisible(true);
    		
			setBackground(color);
			
			//create instances for buttons
			membercnt = new JButton("Total Number Of Members");
			itemschkdout = new JButton("Items Checked Out");
			finesCollected = new JButton("Fines Collected");
			itemsByCategory = new JButton("Item Count by Category");
			bookCheckedOutMost = new JButton("Books Checked Out The Most");
			logout = new JButton("LogOut");
			
			//create instances for button handler
			//handler1 = new AdminButtonHandler1();
			/*handler2 = new AdminButtonHandler1();
			handler3 = new AdminButtonHandler1();
			handler4 = new AdminButtonHandler1();
			handler5 = new AdminButtonHandler1();
			handler6 = new AdminButtonHandler2();
			handler7 = new AdminButtonHandler3();*/
			
			membercnt.addActionListener(new AdminMemberCountHandler());
			itemschkdout.addActionListener(new AdminItemsCheckedOutHandler());
			finesCollected.addActionListener(new FineCollectedHandler());
			itemsByCategory.addActionListener(new TotalNumberOfItemsInEveryCategoryHandler());
			bookCheckedOutMost.addActionListener(new AdminBooksCheckedOutHandler());
			logout.addActionListener(new LogOutHandler());
			adminClear.addActionListener(new AdminClearHandler());
				
		}
		
		public void setAdminTitlePanel()
		{
			mainLbl = new JLabel("ADMINISTRATOR FUNCTIONS");
			mainLbl.setFont(new Font("Times New Roman", Font.BOLD, 40));
			mainLbl.setForeground(Color.BLACK);
			adminTitlePanel.add (mainLbl);
		}
		
		public void setFunctionPanel()
		{
			adminFunctionPanel.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
			add(Box.createRigidArea(new Dimension(20,50)));
			adminFunctionPanel.add(membercnt);
			add(Box.createRigidArea(new Dimension(20,50)));
			adminFunctionPanel.add(itemschkdout);
			add(Box.createRigidArea(new Dimension(20,50)));
			adminFunctionPanel.add(finesCollected);
			add(Box.createRigidArea(new Dimension(20,50)));
			adminFunctionPanel.add(itemsByCategory);
			add(Box.createRigidArea(new Dimension(20,50)));
			adminFunctionPanel.add(bookCheckedOutMost);
			add(Box.createRigidArea(new Dimension(20,50)));
			adminFunctionPanel.add(logout);
			add(Box.createRigidArea(new Dimension(20,50)));
			adminFunctionPanel.add(adminClear);
		
		}
		
		public void setAdminDisplayPanel()
		{
			adminDisplayPanel.setLayout(new FlowLayout());
			adminDisplay.setFont(new Font("Times New Roman", Font.BOLD, 17));
			adminDisplay.setForeground(Color.blue);
			adminDisplay.setBackground(Color.LIGHT_GRAY);
			add(Box.createRigidArea(new Dimension(0, 0)));
			//adminDisplayPanel.add(adminDisplay);
			
		}
		
			
	}

}
